var express = require('express');
var router = express.Router();
var connection = require('../lib/utils/DbconnectUtil');
var moment = require('moment');
var _ = require('underscore');

router.get('/yearDonation', function(req, res, next) {
  var sqlStr = 'select sum(total_fee) yearTotalMoney from t_order where status = 1 and Year(start_time) = ?';
  var currentYear = new Date().getFullYear();
  connection().query(sqlStr, [currentYear], function (err, results) {
    var resultData = {};
        if (err) {
          console.log(err);
          resultData = {code : -1, data : 0, message:"query exception"};

        } else {
          resultData = {code : 0, data : results[0]};
        }
    res.send(resultData);
  });
});

router.get('/monthDonation', function(req, res, next) {
  var sqlStr = "select sum(total_fee) monthTotalMoney from t_order where status = 1 and DATE_FORMAT(start_time,'%Y-%m') = ?";
  var yearMonth = moment(new Date()).format('YYYY-MM');
  connection().query(sqlStr, [yearMonth], function (err, results) {
    var resultData = {};
    if (err) {
      console.log(err);
      resultData = {code : -1, data : 0, message:"query exception"};

    } else {
      resultData = {code : 0, data : results[0]};
    }
    res.send(resultData);
  });
});

router.get('/allDonation', function(req, res, next) {
  var sqlStr = "select sum(total_fee) totalMoney from t_order where status = 1 ";
  connection().query(sqlStr, function (err, results) {
    var resultData = {};
    if (err) {
      console.log(err);
      resultData = {code : -1, data : 0, message:"query exception"};

    } else {
      resultData = {code : 0, data : results[0]};
    }
    res.send(resultData);
  });
});

router.get('/latestDonations', function(req, res, next) {
  var limit = req.query.limit ;
  if(parseInt(limit).toString() != limit  || parseInt(limit) < 0){
    limit = 20;
  }
  else{
    limit = parseInt(limit);
  }

  var sqlStr = "select * from t_order where status = 1 and total_fee >= 10000 order by start_time desc limit ? ";
  connection().query(sqlStr,[limit], function (err, results) {
    var resultData = {};
    if (err) {
      console.log(err);
      resultData = {code : -1, data : 0, message:"query exception"};

    } else {
      _.forEach(results,function (result) {
        result.total_fee = parseFloat(result.total_fee)/100;
        result.start_time = moment(result.start_time).format('YYYY-MM-DD HH:mm:ss');
        result.end_time = moment(result.end_time).format('YYYY-MM-DD HH:mm:ss')
      })

      resultData = {code : 0, data : results};
    }
    res.send(resultData);
  });
});

module.exports = router;
